package com.kwin.rpcserver.netty.code;

import com.alibaba.fastjson.JSON;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;

/**
 * @author : wangkai
 * @version V1.0
 * @Package com.kwin.rpc.netty.code
 * @Description:
 * @date 2021年06月22日 14:09
 **/
public class JSONDecoder extends LengthFieldBasedFrameDecoder {
    public JSONDecoder() {
        super(65535, 0, 4, 0, 4);
    }
    
    @Override
    protected Object decode(ChannelHandlerContext ctx, ByteBuf in)
        throws Exception {
        ByteBuf decode = (ByteBuf) super.decode(ctx, in);
        if(decode == null) {
            return null;
        }
        int len = decode.readableBytes();
        byte[] bytes = new byte[len];
        decode.readBytes(bytes);
        Object parse = JSON.parse(bytes);
        return parse;
    }
}
